import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterdemo/refresh/pull_to_refresh/pull2refresh_footer.dart';
import 'package:flutterdemo/refresh/pull_to_refresh/pull2refresh_header.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter_screenutil/screenutil.dart';

void main() {
  runApp(MaterialApp(
    home: Pull2Refresh(),
  ));
}

class Pull2Refresh extends StatefulWidget {
  @override
  _Pull2RefreshState createState() => _Pull2RefreshState();
}

class _Pull2RefreshState extends State<Pull2Refresh> {
  List<String> items = [
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8"
  ];
  RefreshController _refreshController = RefreshController(initialRefresh: false);

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 5000));
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 5000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    items.add((items.length + 1).toString());
    if (mounted) setState(() {});
    _refreshController.loadComplete();
  }

  ScrollController _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 1080, height: 1920, allowFontScaling: false);
    return Scaffold(
      appBar: AppBar(
        title: Text("pull2refresh"),
      ),
      body: SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: Pull2RefreshHeader(),
        footer: Pull2RefreshFooter(),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: ListView.builder(
          controller: _scrollController,
          itemBuilder: (c, i) => Card(child: Center(child: Text(items[i]))),
          itemExtent: 100.0,
          itemCount: items.length,
//          physics: `NeverScrollableScrollPhysics`(),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _scrollTo5,
        child: Text("scrollTo5"),
      ),
    );
  }

  void _scrollTo5() {
    _scrollController.animateTo(100.0*5, duration: Duration(milliseconds: 500), curve: Curves.ease);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }
}
